package org.cuit.lmq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.cuit.lmq.domain.common.Result;
import org.cuit.lmq.domain.po.HomePage;
import org.cuit.lmq.domain.vo.HomePageVo;
import org.cuit.lmq.service.HomePageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Seon
 * @date 2023/3/15
 */
@Slf4j
@RestController
@RequestMapping("/home")
public class HomePageController {

    @Autowired
    private HomePageService homePageService;
    @GetMapping("/information")
    public Result<?> getHomePage(@RequestParam("currentPage") Integer currentPage,
                                 @RequestParam("pageSize") Integer pageSize) {
        Page<HomePage> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        LambdaQueryWrapper<HomePage> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(HomePage::getId, HomePage::getHeats, HomePage::getTitle, HomePage::getFrontCover, HomePage::getType);
        wrapper.orderByDesc(HomePage::getHeats);
        homePageService.page(page, wrapper);
        List<HomePageVo> collect = page.getRecords().parallelStream().map(HomePageVo::new).collect(Collectors.toList());

        Page<HomePageVo> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage, "records");
        voPage.setRecords(collect);

        return Result.success(voPage);
    }

    @GetMapping("/information/detail")
    public Result<?> getHomePage(@RequestParam("id") Long id) {
        // 这里才是真正返回po
        HomePage detail = homePageService.getById(id);
        //并且每次访问之后都会增加一次访问量，这样子就变为了热点资讯。
        Long heats = detail.getHeats();
        detail.setHeats(++ heats);
        try {
            homePageService.updateById(detail);
        } catch (Exception e) {
            log.error("id为{}的文章无法增加点击量，请检查程序", detail.getId());
        } finally {
            return Result.success(detail);
        }
    }
}
